<?php


namespace app\api\library\withdraw\withdraw;


use app\admin\model\MallWithdrawRecord;
use app\api\model\MallTradeRecordLog;
use app\api\model\MallUser;
use think\Exception;
use think\facade\Db;
use think\facade\Filesystem;

class V
{
    public static function run($param)
    {
        
        $userId     = _checkEmptyParam($param[ 'userId' ], '用户不能为空');
        $withdrawId = _checkEmptyParam($param[ 'withdrawId' ], '用户不能为空');
        $amount     = _checkEmptyParam($param[ 'amount' ], '收款金额不能为空');
        $code       = _checkEmptyParam($param[ 'code' ], '验证码不能为空');
        $mobile     = MallUser::where('id', $userId)->value('mobile');
        //查询用户最新的一次验证码
//        $userCode = Db::name('mall_mobile_msg')->where([['mobile', '=', $mobile], ['code', '=', $code]])->find();
//        if (empty($userCode)) {
//            _outPut(204, '', '验证码错误');
//        }
//        if ($userCode[ 'expire_time' ] < time()) {
//            _outPut(204, '', '验证码已过期');
//        }
        $withdrawType = (array) Db::name('mall_withdraw_info')
            ->where([['id', '=', $withdrawId]])
            ->order(['current' => 'desc', 'id' => 'desc'])
            ->field('id,name,type,account,image,current')
            ->find();
        $balance      = MallUser::where('id', $userId)->value('balance');
        $amount       = $amount * 100;
        $surBalance   = $balance - $amount;
        $addData      = [
            'user_id'     => $userId,
            'name'        => $withdrawType[ 'name' ],
            'type'        => $withdrawType[ 'type' ],
            'status'      => 0,
            'amount'      => $amount,
            'balance'     => $surBalance,
            'account'     => $withdrawType[ 'account' ],
            'image'       => $withdrawType[ 'image' ],
            'create_time' => time(),
            'update_time' => time(),
        ];
        try {
            //开启事务
            Db::startTrans();
            MallTradeRecordLog::addRecord($userId, 0, $amount, $surBalance, $withdrawType[ 'type' ] + 13);
            //减去余额
            if (false === MallUser::where([['id', '=', $userId]])->update(['balance' => $surBalance])) {
                _throwNewException('提现申请失败');
            }
            if (false === MallWithdrawRecord::insert($addData)) {
                _throwNewException('提现申请失败');
            }
            // 提交事务
            Db::commit();
        } catch (Exception $e) {
            // 回滚事务
            Db::rollback();
            _outPut(204, '', $e->getMessage());
        }
        _outPut(200);
    }
    
}